import axios from 'axios'
import QS from 'qs'
import settins from '@/settings'
import store from '@/store'
import { token} from './auth'

const request = axios.create({
    baseURL: process.env.ENV === 'development' ? process.env.APP_BASE_API : '/',
    timeout: settins.timeout
})

/**
 * 请求拦截器
 * 
 */
request.interceptors.request.use(config=>{
    if(config.method === 'post'){
        config.data = QS.stringify(config.data)
    }
    if(token()){
        config.headers['Authorization'] = token()
    }
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    return config
},error=>{
    console.log(error)
    Promise.reject(error)
})

/**
 * 响应拦截器
 */
request.interceptors.response.use(response=>{
    const code = response.status
    if(code<200||code>300){
        //错误提示自定义
        return Promise.reject('error')
    }
    return response
},error=>{
    let code = 0
    try{
        code = error.response.data.status
    }catch(e){
        if (error.toString().indexOf('Error: timeout') !== -1) { //请求超时
            return Promise.reject(error)
          }
    }
    if(code){
        if(code == 401) { //登录过期
            store.dispatch('LogOut').then(() => {
                location.reload() // 为了重新实例化vue-router对象 避免bug
            })
        }

    }
    return Promise.reject(error)
})

export default request